<template>

	<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

		<el-form-item label="用户名" prop="username">
			<el-input v-model="ruleForm.username"></el-input>
		</el-form-item>
		<el-form-item label="密码" prop="password">
			<el-input v-model="ruleForm.password"></el-input>
		</el-form-item>
		<el-form-item label="邮箱" prop="email">
			<el-input v-model="ruleForm.email"></el-input>
		</el-form-item>
		<el-form-item label="手机" prop="mobile">
			<el-input v-model="ruleForm.mobile"></el-input>
		</el-form-item>
	</el-form>
</template>

<script>
export default {
	name: 'Verifications',
	data() {
		var checkEmail = (rule, value, callback) => {

			const regEmail = /^([a-zA-Z]|[0-9])(\w)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/

			if (!value) {
				return callback(new Error('邮箱不能为空'))
			}
			if (regEmail.test(value)) {
				return callback()
			}
			callback(new Error('邮箱格式错误'))
		}
		var checkMobile = (rule, value, callback) => {
			const regEmail = /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/
			if (!value) {
				return callback(new Error('手机号不能为空'))
			}
			if (regEmail.test(value)) {
				return callback()
			}
			callback(new Error('手机号格式错误'))
		}
		return {
			reset: this.$store.state.Users.addUser,
			ruleForm: {
				username: '',
				password: '',
				email: '',
				mobile: '',
			},
			rules: {
				username: [
					{ required: true, message: '用户名不能为空', trigger: 'blur' },
					{ max: 10, message: '用户名长度最大为10', trigger: 'blur' },
				],
				password: [
					{ required: true, message: '密码不能为空', trigger: 'blur' },
					{ min: 6, message: '密码超度至少为6位', trigger: 'blur' },
				],
				email: [{ validator: checkEmail, trigger: 'blur' }],
				mobile: [{ validator: checkMobile, trigger: 'blur' }],
			},
		}
	},

	mounted() {
		this.$bus.$on('cancle', () => {
			this.$refs.ruleForm.resetFields()
		})
		this.$bus.$on('addUser', () => {
			this.$refs.ruleForm.validate(data => {
				this.$bus.$emit('isData', data, {
					username: this.ruleForm.username,
					password: this.ruleForm.password,
					email: this.ruleForm.email,
					mobile: this.ruleForm.mobile,
				})
			})
		})
	},
}
</script>
